-- A program to bubblesort an array of numbers
--
-- 5000 = size of array to be sorted
-- 5004 = beginning of array
-- 
-- 
--
Begin Assembly
-- Data is at Org 5000
-- Size of array at 5000
-- R1 is forward address incrementer
ADDI R1, R0, 5000
-- Load number of elements into R2
LW R2, 0(R1)
-- Multiply num of elements by 4, since each element is 4 bytes: store in R3
SLL R3, R2, 2
--Store address of last element of array in R4 (add first element to size in bytes)
ADD R4, R1, R3
-- R1 is address of beginning of array of numbers now
ADDI R1, R1, 4
-- make sure there's more than 2 elements before we go into the loop
-- subtract first element address with last element address
SUB R10, R4, R1
BLEZ R10, PostOuter
LABEL OuterLoop
--Store address of last element of array (for decrementing) in R5
ADD R5, R4, R0
-- make sure inner loop should enter
--subtract outer counter from inner (branch if i<=j)
SUB R10, R5, R1
BLEZ R10, PostInner
--load first value
LW R6, 0(R5)
LABEL InnerLoop
--decrement address (R5)
ADDI R5, R5, -4
--move newer value to older slot (R7)
ADD R7, R6, R0
--load new value into (R6)
LW R6, 0(R5)
--subtract R6 (new) from R7 (old) for compare
SUB R10, R7, R6
--branch and dont flip the numbers if result is 0 or negative (means old >= new)
BLEZ R10, NoFlip
--body of if statement: flip the numbers
--R8 is temp: flip R6 and R7
ADD R8, R7, R0
ADD R7, R6, R0
ADD R6, R8, R0
LABEL NoFlip
--Store the older value back into the array
SW R7, 4(R5)
--loop if inner counter greater than outer
SUB R10, R5, R1
BGTZ R10, InnerLoop
--store final value before moving on
SW R6, 0(R5)	
LABEL PostInner
--increment the outer loop counter
ADDI R1, R1, 4
--loop if the outer counter has not reached the end of the array
SUB R10, R4, R1
BGTZ R10, OuterLoop
LABEL PostOuter
HALT
End Assembly
Begin Data 5000 44
11
0
23
71
33
5
93
82
34
13
111
23
End Data